package com.huabo.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.ServletRequestUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.Map;
import java.util.Random;

/**
 * Created by Jackie Liu on 2017/8/11.
 */
public class WebUtils {

    private WebUtils() {

    }

    @SuppressWarnings("unchecked")
	public static void gainParams(HttpServletRequest request, Map<String, Object> paramsMap) {
        Enumeration<String> params = request.getParameterNames();
        boolean isGet = request.getMethod().toUpperCase().equals("GET") ? true : false;
        while(params.hasMoreElements()){
            String paramName = (String) params.nextElement();
            String paramValue = ServletRequestUtils.getStringParameter(request, paramName, null);
            if (paramValue != null && isGet) {
                try {
                    //paramValue = new String(paramValue.getBytes("ISO8859-1"), "UTF-8");
                    //System.out.println("#########paramValue = " + paramValue);
                    paramValue = URLDecoder.decode(paramValue, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            //System.out.println("paramName = " + paramName + " paramValue = " + paramValue);
            paramsMap.put(paramName, paramValue);
        }
    }
    
    /**
     * <p>Description: 获取项目请求根路径，如：http://localhost:8080/project</p>
     * @param request HttpServletRequestd对象
     * @return
     */
    public static String getRequestRootPath(HttpServletRequest request) {
        StringBuffer sb = new StringBuffer();
        sb.append(request.getScheme()).append("://")
                .append(request.getServerName()).append(":")
                .append(request.getServerPort())
                .append(request.getContextPath());
        return sb.toString();
    }

    /**
     * 生成随机字符串
     * @param length 生成字符串的长度
     * @return
     */
    public static String getRandomString(int length) {
        String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 将文件转成base64 字符串
     * @param path 文件路径
     * @return
     * @throws Exception
     */
    public static String encodeBase64File(String path) {
        File file = new File(path);
        FileInputStream inputFile = null;
        try {
            inputFile = new FileInputStream(file);
            byte[] buffer = new byte[(int)file.length()];
            inputFile.read(buffer);
            return Base64.encodeBase64String(buffer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputFile);
        }
        return null;
    }

    public static Long[] toLongArray(String[] array) {
        if (array == null || array.length == 0) {
            return null;
        }
        Long[] arr = new Long[array.length];
        for (int i = 0; i < array.length; i ++) {
            arr[i] = Long.valueOf(array[i]);
        }
        return arr;
    }
}
